<template>
  <el-space wrap direction="vertical" alignment="normal" fill>
    <el-row class="dev-tool-box">
      <!--   搜索     -->
      <el-form :inline="true" class="demo-form-inline" :model="devices.searchData">
        <el-form-item>
          <el-button type="primary" @click="openAddDevDialog">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refreshCurrentPage">刷新</el-button>
        </el-form-item>
        <el-form-item label="imei">
          <el-input v-model="devices.searchData.imei" placeholder="请输入imei" clearable/>
        </el-form-item>
        <el-form-item label="name">
          <el-input v-model="devices.searchData.name" placeholder="请输入搜索的name" clearable/>
        </el-form-item>
        <el-form-item label="udid">
          <el-input v-model="devices.searchData.udid" placeholder="请输入搜索的udid" clearable/>
        </el-form-item>

        <el-form-item label="status">
          <el-select
              v-model="devices.searchData.status"
              multiple
              clearable
              collapse-tags
              placeholder="Select"
              popper-class="custom-header"
              :max-collapse-tags="1"
              style="width: 240px"
              @change="onStatusChange"
          >
            <template #header>
              <el-checkbox
                  v-model="selectAllStatus"
                  :indeterminate="indeterminate"
                  @change="selectAllStatusChange"
              >
                All
              </el-checkbox>
            </template>
            <el-option
                v-for="item in allDevStatus"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-card style="width: 40%">

      <el-space wrap>
        <el-card class="dev-card" v-for="dev in devices.list" :key="dev.id">
          <template #header>
            <div class="card-header">
              <h3>IMEI: {{ dev.imei }}</h3>
            </div>
          </template>
          <div>Udid: {{ dev.udid }}</div>
          <div>Name: {{ dev.name }}</div>
          <template #footer class="dev_footer">
            <el-row :gutter="0">
              <el-col :span="12">
                <div :style="setDevStatusColor(dev.status)">{{ dev.status }}</div>
              </el-col>
              <el-col :span="6">
                <el-button type="info" size="small" @click="refreshDevice(dev.id)">刷新</el-button>
              </el-col>
              <el-col :span="6">
                <el-button type="danger" size="small" @click="deleteDevice(dev.id)">删除</el-button>
              </el-col>


            </el-row>
          </template>
        </el-card>
      </el-space>
      <el-pagination
          :current-page="pagination_index"
          @current-change="currentChange"
          @size-change="sizeChange"
          :total="devices.otherData.count"
          layout="prev, pager, next, jumper, total">
      </el-pagination>
    </el-card>
  </el-space>

  <el-dialog v-model="addDevDialogShow" title="添加设备" width="1000" :before-close="addDevDialogClose">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item justify="start">
        <el-button type="primary" @click="getAdbDevices" :disabled="getAdbDevLoading >0">刷新</el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model="connectDevInputData" placeholder="未找到? 输入IP尝试连接" clearable justify="end"/>
      </el-form-item>

      <el-form-item v-loading="connectDevLoading">
        <el-button type="primary" @click="connectDevice(connectDevInputData)" :loading="connectDevLoading >0">连接
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="adbDeviceList.list"
        stripe
        style="width: 100%"
        v-loading="getAdbDevLoading"
        element-loading-text="获取已连接的设备中..."
        @selection-change="addDevSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="udid" label="udid" width="180"/>
      <el-table-column prop="name" label="name" width="180"/>
      <el-table-column prop="imei" label="imei" width="180"/>
      <el-table-column prop="wifi" label="wifi" width="180"/>
      <el-table-column prop="status" label="status" width="180"/>
    </el-table>
    <el-button type="primary" @click="addSelectedDevice(selectedAddDev)" :disabled="addSelectedLoading >0">添加
    </el-button>
  </el-dialog>
</template>


<script setup lang="ts">
import {onMounted, reactive, ref, watch} from "vue";
import {DeviceI, InitAdbDeviceList, InitDeviceList} from "@/type/device.ts";
import {
  apiAddDevice,
  apiDeleteDevice,
  apiGetDeviceDetail,
  apiGetDeviceList,
  apiGetDeviceStatuses
} from "@/request/device/api.ts";
import {CheckboxValueType} from "element-plus";
import {apiConnectAdbDevice, apiGetAdbDevices} from "@/request/device/adb_device_api.ts";
import {showMsg, ShowType} from "@/plugin/message.ts";
// import {apiConnectAdbDevice, apiGetAdbDevices} from "@/request/device/adb_device_api.ts";

const isInitialized = ref(false); // 组件是否初始化

const devices = reactive(new InitDeviceList())
const getDevices = (params = {}) => {
  // 默认参数
  const defaultParams = {
    page: 1,         // 当前页码
    pageSize: 10,    // 每页数据量
    filter: '',      // 过滤条件
  };

  // 合并传入的参数与默认参数
  const finalParams = {...defaultParams, ...params};
  apiGetDeviceList(finalParams).then(
      (res) => {

        devices.list = res.results
        devices.otherData.count = res.count
        // devices.otherData.page = res.page
        devices.otherData.pageSize = res.pageSize

      }
  )
}
onMounted(
    () => {
      if (!isInitialized.value) {
        getDevices()
        getAllDevStatuses()
        isInitialized.value = true;
      }
    }
)

const currentChange = (p: number) => {
  devices.otherData.page = p
  pagination_index.value = p
  getDevices({page: devices.otherData.page, pageSize: devices.otherData.pageSize})
}

const sizeChange = (pSize: number) => {
  devices.otherData.pageSize = pSize
}

// 根据设置设备状态设置状态的style
const setDevStatusColor = (text) => {

  if (text.includes("Online")) {
    return {'color': 'green'};
  } else if (text.includes("Offline")) {
    return {'color': 'red'};
  } else if (text.includes('Error')) {
    return {'color': '#bfb86e'}
  }
}

// const ShowType = {
//   success: 'success',
//   warning: 'warning',
//   info: 'info',
//   error: 'error'
// }
// const showMsg = (showType: ShowType, msg: string, showClose: boolean = true) => {
//   const options = {message: msg, showClose: showClose};
//   switch (showType) {
//     case ShowType.success:
//       ElMessage.success(options);
//       break;
//     case ShowType.warning:
//       ElMessage.warning(options);
//       break;
//     case ShowType.info:
//       ElMessage.info(options);
//       break;
//     case ShowType.danger:
//       ElMessage.error(options);
//       break;
//     default:
//       ElMessage.info(options);
//       break;
//   }
// };
// const addDevice = () => {
//   apiAddDevice(addDeviceData.value).then(
//       (res) => {
//         addDevDialogShow.value = false
//         getDevices({page: pagination_index.value})
//         showMsg(ShowType.success, '添加成功!')
//       }
//   )
// }
const pagination_index = ref(1)
const refreshCurrentPage = () => {

  getDevices({page: pagination_index.value})
  showMsg(ShowType.Success, '刷新成功!')
}
const refreshDevice = (id) => {
  apiGetDeviceDetail(id).then(
      () => {
        getDevices({page: pagination_index.value})
        showMsg(ShowType.success, '刷新成功!')
      }
  )

}
const deleteDevice = (id) => {
  {
    const lastPage = Math.floor(devices.otherData.count / devices.otherData.pageSize)
    const pageLastDevice = devices.otherData.count % devices.otherData.pageSize
    let allPage = lastPage
    if (pageLastDevice != 0) {
      allPage += 1
    }
    if (pagination_index.value === allPage && pageLastDevice == 1) {
      pagination_index.value -= 1
    }

    apiDeleteDevice(id).then(
        () => {
          getDevices({page: pagination_index.value})
          showMsg(ShowType.success, '删除成功!')
        }
    )
  }
}

const allDevStatus = ref([])

async function getAllDevStatuses() {
  const result = await apiGetDeviceStatuses()
  allDevStatus.value = result?.data

}

const indeterminate = ref(false)
const selectAllStatusChange = (val: CheckboxValueType) => {
  devices.searchData.status = val ? allDevStatus : [];
  indeterminate.value = false;

}

const onStatusChange = () => {
  const selectedStatusCount = devices.searchData.status.length;
  selectAllStatus.value = selectedStatusCount === allDevStatus.value.length;
  indeterminate.value = selectedStatusCount > 0 && selectedStatusCount < allDevStatus.value.length;

}
const selectAllStatus = ref(false)
// ==========================================添加设备弹窗==========================================
const searchSubmit = () => {
  let arr: DeviceI[] = []
  if (devices.searchData.name || devices.searchData.status || devices.searchData.imei || devices.searchData.udid) {
    if (devices.searchData.name) {
      arr = devices.list.filter((object) => {
        return object.name.indexOf(devices.searchData.name) != -1
      })
    }
    if (devices.searchData.status) {
      arr = devices.list.filter((object) => {
        return object.status.indexOf(devices.searchData.status) != -1
      })
    }
    if (devices.searchData.imei) {
      arr = devices.list.filter((object) => {
        return object.imei.indexOf(devices.searchData.imei) != -1
      })
    }
    if (devices.searchData.udid) {
      arr = devices.list.filter((object) => {
        return object.udid.indexOf(devices.searchData.udid) != -1
      })
    }
  } else {
    arr = devices.list
  }

  devices.otherData.count = arr.length
  devices.list = arr

  watch(
      [() => devices.searchData.status, () => devices.searchData.name, () => devices.searchData.imei, () => devices.searchData.udid],
      () => {
        if (devices.searchData.name && devices.searchData.status && devices.searchData.imei && devices.searchData.udid) {
          getDevices({page: pagination_index.value, pageSize: devices.otherData.pageSize})
        }
      }
  )
}

// ==========================================添加设备弹窗==========================================
const addDevDialogShow = ref(false)
const getAdbDevLoading = ref(0)
const openAddDevDialog = () => {
  addDevDialogShow.value = true
  getAdbDevices()
}
const adbDeviceList = reactive(new InitAdbDeviceList())

async function getAdbDevices() {
  try {
    if (getAdbDevLoading.value > 0) {
      return
    }
    getAdbDevLoading.value++
    adbDeviceList.list = await apiGetAdbDevices()
  } catch (err) {
    showMsg(ShowType.warning, '获取设备失败!' + err.message)
    console.log("获取adb devices报错：", err)
    return

  } finally {
    getAdbDevLoading.value = Math.max(0, getAdbDevLoading.value - 1)
  }
}

const connectDevInputData = ref('')
const connectDevLoading = ref(0)

async function connectDevice(ip) {
  try {
    if (!ip) {
      showMsg(ShowType.warning, '请输入ip地址!')
      return
    }
    connectDevLoading.value++
    const result = await apiConnectAdbDevice(ip)
    print("fasdada: ", result)
    if (result?.status == 'success') {
      showMsg(ShowType.success, '连接成功!')
    } else {
      showMsg(result?.msg.w)
    }

  } catch (error) {
    showMsg(ShowType.warning, '连接失败!' + error.message)
    console.log("连接设备报错：", error)
    return
  } finally {
    connectDevLoading.value = Math.max(0, connectDevLoading.value - 1)
  }
}

const selectedAddDev = ref()

// 获取添加设备时选中的设备
const addDevSelectionChange = (selection) => {

  selectedAddDev.value = selection
  console.log("selectedAddDev: ", selectedAddDev.value)
}
const addSelectedLoading = ref(0)

async function addSelectedDevice(data) {
  try {
    console.log(data)
    if (!data) {
      showMsg(ShowType.warning, "未选择设备!")
      return
    }
    addSelectedLoading.value++

    const add_res = await apiAddDevice(data)
    console.log('add_res: ', add_res)
    if (add_res.successful?.length > 0) {
      add_res.successful.forEach(item => {
        showMsg(ShowType.success, (item.name + '添加成功!'))
      })
      // 添加成功后重新获取设备列表

    }
    if (add_res.failed?.length > 0) {
      add_res.failed.forEach(item => {
        showMsg(ShowType.warning, ('添加失败!' + item.errors))
      })
    }

  } catch (err) {
    showMsg(ShowType.warning, '添加失败!', err)
  } finally {
    addSelectedLoading.value = Math.max(0, addSelectedLoading.value - 1)

  }

}

// 关闭add dev dialog
const addDevDialogClose = () => {
  selectedAddDev.value = null
  addDevDialogShow.value = false
  getDevices({page: pagination_index.value, pageSize: devices.otherData.pageSize})
}

</script>


<style scoped>

.dev-card {
  width: 250px;
  max-width: 480px;
}

</style>